﻿using SqlSugar;
using System.Configuration;
using System.Linq;

namespace yichu_front
{
    public static class SqlSugarHelp
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        public static SqlSugarScope scope = new SqlSugarScope(new ConnectionConfig()
        {
            //ConnectionString = "Data Source=.;Initial Catalog=echu;User ID=sa;Password=sa;Pooling=true;MAX Pool Size=20;Min Pool Size=10;Connection Lifetime=15",//测试连接符字串
            //ConnectionString = "Data Source=36.154.36.194;Initial Catalog=baojia;User ID=sa;Password=SHYCechu!@#;Pooling=true;MAX Pool Size=20;Min Pool Size=10;Connection Lifetime=15",//老连接符字串
            //ConnectionString = "Data Source=192.168.18.200;Initial Catalog=baojias;User ID=sa;Password=:$apr1$gFVfuqen$sm0BO3I/6qWpfR5xL056c.;Pooling=true;MAX Pool Size=20;Min Pool Size=10;Connection Lifetime=15",//防止未更新的 新的符字串
            ConnectionString = ConfigurationManager.ConnectionStrings["echu"].ToString(),
            DbType = DbType.SqlServer,//数据库类型
            IsAutoCloseConnection = true //不设成true要手动close
        },
           db =>
           {
               db.Aop.OnLogExecuting = (sql, pars) =>
        {
            Logger.Info(sql);//输出sql
            Logger.Info(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));//参数
            //string begin = "sql语句为：[" + sql+"]参数为";
            //string end = "";
            //foreach (var item in pars)
            //{
            //    end += "---["+item.ParameterName+"::" + item.Value + "]";
            //}
            //Logger.Info(begin + end);
        };
               db.Aop.OnError = (exp) =>//SQL报错
           {
               Logger.Error(exp.Sql);         
           };
               db.Aop.OnLogExecuted = (sql, p) =>
               {
                   //执行时间超过1秒
                   if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                   {
                       //代码CS文件名
                       var fileName = db.Ado.SqlStackTrace.FirstFileName;
                       //代码行数
                       var fileLine = db.Ado.SqlStackTrace.FirstLine;
                       //方法名
                       var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
                       Logger.Warn("执行超过1s的sql【" + sql + "】代码CS文件名【" + fileName + "】代码行数【" + fileLine +"】");
                       //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息
                   }
               };
           }

           );

        //public static List<User> GetUser() 
        //{
        //    return scope.Queryable<User>().ToList();
        //}
    }
}
